<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
 <%@ include file="/pages/common/common.jsp" %>    
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>树形数据结构(带tab选项)</title>
	<link rel="stylesheet" href="<%=request.getContextPath()%>/scripts/ztree/css/demo.css" type="text/css">
	<link rel="stylesheet" href="<%=request.getContextPath()%>/scripts/ztree/css/zTreeStyle.css" type="text/css">
	<link rel="stylesheet" href="<%=request.getContextPath()%>/styles/base.css" type="text/css">
	<link rel="stylesheet" href="<%=request.getContextPath()%>/styles/lazy.css" type="text/css">
	<script type="text/javascript" src="<%=request.getContextPath()%>/scripts/jquery/jquery-1.7.1.min.js"></script>
	<script type="text/javascript" src="<%=request.getContextPath()%>/scripts/ztree/js/jquery.ztree.all-3.5.min.js"></script>

	<style type="text/css">
		.content_wrap {width: 580px;height:360px;}
		.content_wrap div.left{float: left;width: 235px;height: 350px;padding-left: 50px;}
		.content_wrap div.right{float: right;width: 235px;height: 350px;}

		.tab-ui{
			width: 400px;
			height: 300px;
			position: relative;
		}
		.tab-title{
			border-top-right-radius:8px;
			float: left;
			border: solid 1px #7EABCD;
			background: #c5dbec;
			padding: 5px;
			font-weight: bold;
			color: #5c5c5c;
			margin: 1px;
			font-size: 14px;
		}
		.tab-title:hover{
			cursor: pointer;
		}
		.tab-title-active{
			background: #7EABCD;
		}
		.content{
			width: 100%;
			height: 100%;
			position: absolute;
			top: 33px;
			left: 1px;
		}
		.tab-content{
			width: 610px;height:320px;
			padding: 10px;
			border-top: solid 1px #c5dbec;
		}
		.tab-content div.left{float: left;width: 235px;height: 350px;padding-left: 30px;}
		.tab-content div.right{float: right;width: 235px;height: 350px;}
	</style>
<script type="text/javascript">
var setting = {
		async: {
			enable: true,
			url:"${pageContext.request.contextPath}/rptTools/treeData/tabTreenode/${compSid}/${attrName}/${rightValue}/${parentValue}/0",
			type:"post",
			dataType:"json",
			autoParam:["id"],
			dataFilter: filter
		},
		callback: {
			onAsyncError: onAsyncError,
			onAsyncSuccess: onAsyncSuccess,
			onCheck:onTreeCheck,
			onClick:onTreeClick
		},
		check: {
			enable: true,
			chkboxType: { "Y": "", "N": ""}
		},	
		view: {
			showIcon:true
		},
		data: {
			keep: {
				leaf: true		
			},
			simpleData: {    //主要是为了加载当前登录机构的父节点
				enable:true,  //使用简单数据模式，并且让数据满足父子关系。
				idKey: "id",
				pIdKey: "pid",
				rootPId: null
			}			
		}
	
	};
	if('${isMulti}' == 'true'){
		setting.check.chkStyle = "checkbox";
	} else {
		setting.check.chkStyle = "radio"; //单选
		setting.check.radioType = "all";   //设置整棵树单选
	}
	
  	var isMulit = '${isMulti}';
	var seldDefineName = '${selfDefineName}';
	var selfDefineValue = '${selfDefineValue}';
	var readOnly = '${readOnly}';
	var needSearch = '${needSearch}';
	var treeParams = '${treeParams}';
	var selectTab = 1;  // 选中的tab页
    var compSid = '${compSid}';
    var attrName = '${attrName}';
    var treeNameList = seldDefineName.split(",");
    var treeIdList = selfDefineValue.split(",");
    var tabTreeNames = '${tabTreeNameMap}';
    var tabTreeIds = '${tabTreeIdMap}';
    var tabFirstClick = '${tabFirstClick}';
    var jsonTreeNames = JSON.parse(tabTreeNames);
    var jsonTreeIds = JSON.parse(tabTreeIds);
    var jsonClick = JSON.parse(tabFirstClick);
	var multiTreeMode = '${multiTreeMode}';

	function filter(treeId, parentNode, childNodes) {
		if (!childNodes) return null;
		for (var i=0, l=childNodes.length; i<l; i++) {
			childNodes[i].name = childNodes[i].name.replace(/\.n/g, '.');
		}
		return childNodes;
	}
	
	function onAsyncError(event, treeId, treeNode, XMLHttpRequest, textStatus, errorThrown) {
		alert("error");
	}
	function onAsyncSuccess(event, treeId, treeNode, msg) {
		defaultcheck(treeNode, treeId);
	}
	
	function onTreeCheck(event,treeId,treeNode){
        var treeNames = jsonTreeNames[selectTab];
        var treeIds = jsonTreeIds[selectTab];
        var arrTabNames = treeNames.split(",");
        var arrTabIds = treeIds.split(",");
		
		if(isMulit == 'false'){
			$("select[id=selectedBox_div" + selectTab + "] option").each(function(i){
				$(this).remove();
			});
		}
		if(treeNode.checked){
			$("#selectedBox_div" + selectTab).append("<option value=\""+treeNode.id+"\">"+treeNode.name+"</option>");
		    treeNameList.push(treeNode.name);
            treeIdList.push(treeNode.id);

            arrTabNames.push(treeNode.name);
            arrTabIds.push(treeNode.id);
            jsonTreeNames[selectTab] = joinArr(arrTabNames);
            jsonTreeIds[selectTab] = joinArr(arrTabIds);
		}
		if(!treeNode.checked)
		$("select[id=selectedBox_div" + selectTab + "] option").each(function(i){
			if($(this).val() == treeNode.id){
				$(this).remove();
                treeNameList.remove($(this).text());
                treeIdList.remove($(this).val());

                arrTabNames.remove($(this).text());
                arrTabIds.remove($(this).val());
                jsonTreeNames[selectTab] = joinArr(arrTabNames);
                jsonTreeIds[selectTab] = joinArr(arrTabIds);
			};
		});
	}
	
	function checkChildNodes(treeNode){
        var treeNames = jsonTreeNames[selectTab];
        var treeIds = jsonTreeIds[selectTab];
        var arrTabNames = treeNames.split(",");
        var arrTabIds = treeIds.split(",");

		if(isMulit == 'true'){
			if(treeNode.checked){
				$("#selectedBox_div" + selectTab).append("<option value=\""+treeNode.id+"\">"+treeNode.name+"</option>");
                treeNameList.push(treeNode.name);
                treeIdList.push(treeNode.id);

                arrTabNames.push(treeNode.name);
                arrTabIds.push(treeNode.id);
                jsonTreeNames[selectTab] = joinArr(arrTabNames);
                jsonTreeIds[selectTab] = joinArr(arrTabIds);
			}
			if(!treeNode.checked) {
				$("select[id=selectedBox_div" + selectTab + "] option").each(function(i){
					if($(this).val() == treeNode.id){
						$(this).remove();
                        treeNameList.remove($(this).text());
                        treeIdList.remove($(this).val());

                        arrTabNames.remove($(this).text());
                        arrTabIds.remove($(this).val());
                        jsonTreeNames[selectTab] = joinArr(arrTabNames);
                        jsonTreeIds[selectTab] = joinArr(arrTabIds);
					};
				});
			}
		}
	}
	
	function onTreeClick(event,treeId,treeNode){
		var treeObj = $.fn.zTree.getZTreeObj("resOrgBox_div" + selectTab);
		if(treeNode.open && isMulit == 'true'){
			if (treeNode.isParent) {
		        var childrenNodes = treeNode.children;
		        if (childrenNodes) {
		            for (var i = 0; i < childrenNodes.length; i++) {
		            	treeObj.checkNode(childrenNodes[i]);
		            	checkChildNodes(childrenNodes[i]);
		            }
		        }
			}
		} else {
			treeObj.expandNode(treeNode);
		}
	}

	/**
     * 已选择的选项默认加载
     */
	function defaultcheck(treeNode, treeId){
        //var selectValues = treeIdList;

        var treeIds = jsonTreeIds[selectTab];
        var selectValues = treeIds.split(",");
		var treeObj = $.fn.zTree.getZTreeObj(treeId);
		if(typeof treeNode == "undefined" || treeNode == null || treeNode == ""){
		    // 如果更节点选择，则默认选中
            var rootNode = treeObj.getNodesByFilter(function (node) {
                return node.level == 0
            }, true);
            for(var j = 0; j < selectValues.length; j++) {
                if(rootNode.id == selectValues[j]) {
                    rootNode.checked = true;
                    treeObj.updateNode(rootNode);
                    break;
                }
            }
			return ;
		} else {
		    // 如果子节点选择，则默认选中
			for(var i = 0; i < treeNode.children.length; i++) {
				for(var j = 0; j < selectValues.length; j++) {
					if(treeNode.children[i].id == selectValues[j]) {
						treeNode.children[i].checked = true;
						treeObj.updateNode(treeNode.children[i]);
						break;
					}
				}
			}
		}
	}

	$(document).ready(function(){
	    jsonClick[1] = '0';
		initTree(1, "1");
	});

	function initTree(active, isFirstLoad) {
	    //alert(tabTreeNames + "==" + tabTreeIds);
        var treeNames = jsonTreeNames[active];
        var treeIds = jsonTreeIds[active];
		if(multiTreeMode == '0' && isFirstLoad == '0') {
			treeNames = '';
			treeIds = '';
            jsonTreeNames[active] = '';
            jsonTreeIds[active] = '';
		}

		// 如果是自定义报表，则树形控件不可选择，且初始化用户自定义的信息
		if(readOnly == '1') {
			$("#searchDiv" + active).css('display','none');
			$("#selectedBox_div" + active).css("height", "300px");
			$("div.left").css('display','none');
			$("div.right").css('float','left');
			$("div.right").css('padding-left','70px');
			var treeName = treeNames.split(',');
			var treeId = treeIds.split(',');
			if(!isEmpty(treeId)) {
				for(var i = 0;i<treeName.length;i++){
					$("#selectedBox_div" + active).append("<option value=\""+treeId[i]+"\">"+treeName[i]+"</option>");
				}
			}
		} else if(readOnly == '0') {
			$("div.left").css('display','');
			$("div.right").css('padding-left','');
			$("div.right").css('float','right');
			if(needSearch == '1') {
				$("#searchDiv" + active).css('display','');
				$("#selectedBox_div" + active).css("height", "323px");
                $("#content" + active).css("height", "345px");
			} else {
				$("#searchDiv" + active).css('display','none');
				$("#selectedBox_div" + active).css("height", "300px");
                $("#content" + active).css("height", "320px");
			}
			var treeName = treeNames.split(',');
			var treeId = treeIds.split(',');
			if(!isEmpty(treeId)) {
				for(var i = 0;i<treeName.length;i++){
					$("#selectedBox_div" + active).append("<option value=\""+treeId[i]+"\">"+treeName[i]+"</option>");
				}
			}
			$.fn.zTree.init($("#resOrgBox_div" + active), setting);
		} else {
			$("div.left").css('display','');
			$("div.right").css('padding-left','');
			$("div.right").css('float','right');
			if(needSearch == '1') {
				$("#searchDiv" + active).css('display','');
				$("#selectedBox_div" + active).css("height", "323px");
                $("#content" + active).css("height", "345px");
			} else {
				$("#searchDiv" + active).css('display','none');
				$("#selectedBox_div" + active).css("height", "300px");
                $("#content" + active).css("height", "320px");
			}
			var treeName = treeNames.split(',');
			var treeId = treeIds.split(',');
			if(!isEmpty(treeId)) {
				for(var i = 0;i<treeName.length;i++){
					$("#selectedBox_div" + active).append("<option value=\""+treeId[i]+"\">"+treeName[i]+"</option>");
				}
			}
			$.fn.zTree.init($("#resOrgBox_div" + active), setting);
		}
	}
	
	function checkAndSelOrgTree(){
		var len = $("select[id=selectedBox_div" + selectTab + "] option").length;
		/*if(len == 0){
			alert('请选择数据项');
			return;
		}*/
		var atrNm = $("#autCompAttrName").val();
		var atrId = $("#autCompAttrId").val();
		var selId = "";
		var selText = "";
		/*$("select[id=selectedBox_div" + selectTab + "] option").each(function(i){
			selId = selId + ","+$(this).val();
			selText = selText + "," + $(this).text();
		});*/

        for(var i=0; i<treeIdList.length; i++) {
            if(treeIdList[i] != ',' && treeIdList[i] != '') {
                selId = selId + "," + treeIdList[i];
                selText = selText + "," + treeNameList[i];
            }
        }

		parent.treeDataBack(atrNm,atrId,selText.substring(1),selId.substring(1));
		/* $("#"+atrNm).val(selText.substring(1));
		$("#"+atrId).val(selId.substring(1));
		treeWinDig.close(); */
	}

	function searchTreeInfo(active) {
		var treeName = $("#treeName" + active).val();
		$("div.left").css('display','');
		$("div.right").css('padding-left','');
		$("div.right").css('float','right');

        var index = active - 1;
        // 获取控制数权限的参数值
        var json = JSON.parse(treeParams);
        var index = active - 1;
        var rightParam = json[index].rightParam;
        var parentRightParam = json[index].parentRightParam;
        needSearch = json[index].search;
        var rightValue = parent.getFormValue(rightParam);
        var parentValue = parent.getFormValue(parentRightParam);

        // 重新加载数控件
		if(!isEmpty(treeName)) {
            setting.async.url = "${pageContext.request.contextPath}/rptTools/treeData/tabSearchTree/" + compSid + "/" + attrName + "/" + rightValue + "/" + parentValue + "/" + index + "/" + encodeURI(encodeURI(treeName));
		} else {
            setting.async.url = "${pageContext.request.contextPath}/rptTools/treeData/tabTreenode/" + compSid + "/" + attrName + "/" + rightValue + "/" + parentValue + "/" + index;
		}
		$.fn.zTree.init($("#resOrgBox_div" + active), setting);
	}

    /**
     * 切换TAB页
     * @param total
     * @param active
     */
    function show(total,active){
		for(var i=1;i<total+1;i++){
			$("#tab"+i).removeClass("tab-title-active");
			$("#content"+i).hide();
		}
		$("#tab"+active).addClass("tab-title-active");
		$("#content"+active).show();
		selectTab = active;

        // 获取控制数权限的参数值
        var json = JSON.parse(treeParams);
        var index = active - 1;
        var rightParam = json[index].rightParam;
        var parentRightParam = json[index].parentRightParam;
        needSearch = json[index].search;
        var rightValue = parent.getFormValue(rightParam);
        var parentValue = parent.getFormValue(parentRightParam);

        var clickFlag = jsonClick[active];  // 每个tab是否为第一次点击的标志(当multiTreeMode=0时，第一次点击加载默认值，否值值清空)
		if(multiTreeMode == '0') {
		    if(clickFlag == '1') {
                var treeNames = jsonTreeNames[active];
                var treeIds = jsonTreeIds[active];
                treeNameList = treeNames.split(',');
                treeIdList = treeIds.split(',');
            } else {
                treeNameList = [];
                treeIdList = [];
            }
		}
        // 重新加载数控件
        $("#selectedBox_div" + active).html("");
        setting.async.url = "${pageContext.request.contextPath}/rptTools/treeData/tabTreenode/" + compSid + "/" + attrName + "/" + rightValue + "/" + parentValue + "/" + index;
        initTree(active, clickFlag);
        jsonClick[active] = '0';
	}

    function isEmpty(obj) {
        if(typeof obj == "undefined" || obj == null || obj == ""){
            return true;
        }else{
            return false;
        }
    }

    function joinArr(arr) {
        var str = "";
        for(var i=0; i<arr.length; i++) {
            if(arr[i] != ',' && arr[i] != '') {
                str = str + "," + arr[i];
            }
        }
        return str.substring(1);
    }

	Array.prototype.indexOf = function (val) {
        for(var i=0; i<this.length; i++) {
            if(this[i] == val) {
                return i;
            }
        }
        return -1;
    }
    Array.prototype.remove = function (val) {
        var index = this.indexOf(val);
        if(index > -1) {
            this.splice(index, 1);
        }
    }
</script>
</head>
<body>
	<div class="tab-ui" style="padding-left: 40px;">
		<div class="tab">
			<c:forEach items="${tabs}" var="item" varStatus="status">
				<div class="tab-title <c:if test="${status.count == 1}"> tab-title-active </c:if>" id="tab${status.count}" onclick="show(${tabCnt},${status.count})">
					<a>${item}</a>
				</div>
			</c:forEach>
		</div>
		<div class="content">
			<c:forEach items="${tabs}" var="item" varStatus="status">
				<div class="tab-content" id="content${status.count}" <c:if test="${status.count != 1}"> style="display: none;" </c:if>>
					<div class="left" >
						<fieldset>
							<legend>请选择</legend>
							<div id="searchDiv${status.count}" style="padding-left: 3px;">
								<input type="text" autocomplete="off" id="treeName${status.count}" name="treeName${status.count}" style="width: 160px;">
								<input type="button" class="ui-btn ui-btn-blue" style="width:58px;height: 20px; font-size: 10px;" onclick="searchTreeInfo(${status.count})" id="searchBtn${status.count}" value="搜索"/>
							</div>
							<ul id="resOrgBox_div${status.count}" class="ztree" style="width:210px;height: 290px;margin-left:3px;margin-top:3px;">
							</ul>
						</fieldset>
					</div>
					<div class="right" style="margin-right: 30px;">
						<fieldset>
							<legend>已选择</legend>
							<select id="selectedBox_div${status.count}" multiple="multiple" style="width:223px;height: 300px;margin-left:3px;margin-top:3px;"></select>
						</fieldset>
					</div>
				</div>
			</c:forEach>
		</div>
	</div>
<footer style="margin-top:110px;">
	<div align="center">
		<input type="hidden" id="autCompAttrName" value="${attrNameId }"/>
		<input type="hidden" id="autCompAttrId" value="${hidAttrId }"/>
		<input type="button" class="ui-btn ui-btn-blue" style="width:80px;" id="treeSureBtnId" onclick="checkAndSelOrgTree();" value="确定"/>
	</div>
</footer>	
</body>
</html>